package com.inspect.protocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.alibaba.fastjson.JSONObject;
import com.inspect.log.LogSingleton;
import com.inspect.util.Constant;

public class Inspect_sz extends Inspect_record implements Job {
	private static Logger log = LogSingleton.get_logger(Inspect_sz.class);
	private static Properties prop = new Properties();
	private static String executeUrl = null;
	private static String appCode = null;
	private static String appSecret = null;
	private static String username = null;
	private static String account = null;
	static {
		try {
			prop.load(new InputStreamReader(
					Inspect_sz.class.getClassLoader().getResourceAsStream("sysConfig.properties"), "UTF-8"));
			executeUrl = prop.getProperty("executeUrl");
			appCode = prop.getProperty("appCode");
			appSecret = prop.getProperty("appSecret");
			username = prop.getProperty("username");
			account = prop.getProperty("account");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		long fireTime = context.getFireTime().getTime();
		long nextTime = context.getNextFireTime().getTime();
		// String result = "";
		Map<String, String> command = (Map<String, String>) dataMap.get(Constant.CMD);
		log.info("进来Inspect_sz了");
		if (command.get("IP") != null && !command.get("IP").isEmpty()) {
			try {
				List<String> ips = new ArrayList<String>();
				for (String ip : command.get("IP").split(",")) {
					ips.add(ip);
				}
				String scriptId = command.get("SCRIPT_ID");
				String planId = command.get("PLAN_ID");
				String planStatus = command.get("PLAN_STATUS");
				String scriptName = command.get("SCRIPT_NAME");
				String sysType = command.get("SYS_TYPE");
				//////////////////// 调用蓝鲸接口-开始
				// 1、封装参数
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("app_code", appCode);
				map.put("app_secret", appSecret);
				map.put("username", username);
				map.put("ip_list", ips);// ip是多个，逗号分隔
				map.put("public_script_id", Integer.valueOf(scriptId));
				map.put("account", sysType);// 脚本执行账户名称
				// 2、发送执行脚本请求
				String result2 = Inspect_sz.sendPost(executeUrl, map, "utf-8");// 执行脚本
				log.info("蓝鲸-执行脚本返回格式：" + result2);
				// 3、解析回调参数
				ExecuteScriptEntity entity = JSONObject.parseObject(result2, ExecuteScriptEntity.class);
				// 4、根据taskInstanceId，循环调用脚本执行结果接口
				if ("00".equals(entity.getCode())) {
					int jobId = entity.getData().get("job_id");
					// 5、解析脚本格式
					this.inputResult(jobId, planStatus, fireTime, nextTime, planId, scriptId, scriptName);
				} else {
					log.error("蓝鲸-任务ID为" + planId + "的任务执行脚本失败！");
				}
				//////////////////// 调用蓝鲸接口-结束
			} catch (Exception e) {
				log.error("调用蓝鲸接口出错了" + e.getMessage());
				e.printStackTrace();
			}
		}
		log.info("出去Inspect_sz了");
	}

	public static String getFormatTime(Date date, String format) {
		if (date == null) {
			date = new Date();
		}
		SimpleDateFormat sf = new SimpleDateFormat(format);
		return sf.format(date);
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 * @param param
	 * @param charset
	 * @return
	 */
	public static String sendGet(String url, String param, String charset) {
		String result = "";
		String line;
		StringBuffer sb = new StringBuffer();
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性 设置请求格式
			conn.setRequestProperty("contentType", charset);
			conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			// 设置超时时间
			conn.setConnectTimeout(6000);
			conn.setReadTimeout(6000);
			// 建立实际的连接
			conn.connect();
			// 定义 BufferedReader输入流来读取URL的响应,设置接收格式
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch (Exception e) {
			log.error("蓝鲸——获取脚本URL请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 * @param param
	 * @param charset
	 * @return
	 */
	public static String sendPost(String url, Map<String, Object> map, String charset) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		String line;
		StringBuffer sb = new StringBuffer();
		try {
			log.info("蓝鲸执行脚本URL：" + url + JSONObject.toJSONString(map));
			String param = JSONObject.toJSONString(map);
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性 设置请求格式
			conn.setRequestProperty("contentType", charset);
			conn.setRequestProperty("content-type", "text/plain");
			// 设置超时时间
			conn.setConnectTimeout(6000);
			conn.setReadTimeout(6000);
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应 设置接收格式
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch (Exception e) {
			log.error("蓝鲸——获取脚本URL请求出现异常!" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		// JSONObject.parseObject(new String(result.toByteArray(), "UTF-8"));
		return result;
	}

	@SuppressWarnings("rawtypes")
	public static String sendGet(String url, Map<String, Object> map, String charset) {
		StringBuffer sb = new StringBuffer();
		// 构建请求参数
		if (map != null && map.size() > 0) {
			Iterator it = map.entrySet().iterator(); // 定义迭代器
			while (it.hasNext()) {
				Map.Entry er = (Entry) it.next();
				sb.append(er.getKey());
				sb.append("=");
				sb.append(er.getValue());
				sb.append("&");
			}
		}
		return sendGet(url, sb.toString(), charset);
	}

	// public static String sendPost(String url, Map<String, Object> map, String
	// charset) {
	// StringBuffer sb = new StringBuffer();
	// // 构建请求参数
	// if (map != null && map.size() > 0) {
	// for (Entry<String, Object> e : map.entrySet()) {
	// sb.append(e.getKey());
	// sb.append("=");
	// sb.append(e.getValue());
	// sb.append("&");
	// }
	// }
	// return sendPost(url, sb.toString(), charset);
	// }

	public static void main(String[] args) {
		String url = "http://localhost:8080/portal_sz/inspect/test.do";
		Map<String, Object> map = new HashMap<String, Object>();
		// 接口权限验证
		map.put("app_code", appCode);
		map.put("app_secret", appSecret);
		map.put("username", username);
		map.put("script_id", "1");
		List<String> ips = new ArrayList<String>();
		ips.add("172.16.3.224");
		ips.add("172.16.3.225");
		map.put("ip_list", ips);
		System.out.println("Post请求:" + Inspect_sz.sendPost(url, map, "utf-8"));
	}

}
